<?php

namespace App\Models;

use App\Services\MyPimpableTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
use Tymon\JWTAuth\Contracts\JWTSubject;


class User extends Authenticatable implements JWTSubject
{
    use HasFactory, Notifiable, HasRoles, MyPimpableTrait;

    protected $guard_name = 'api';

    // 可搜索字段
    protected $searchable = ['name', 'email', 'phone'];

    // 定义模糊搜索字段
    protected $vague = ['name', 'email'];

    // 设置默认排序字段
    public $defaultSortCriteria = ['updated_at,desc'];

    // 可排序字段
    protected $sortable = ['id'];

    protected $sortParameterName = 'sortBy';

    protected $fillable = [
        'name',
        'username',
        'id_card',
        'phone',
        'status',
        'email',
        'password',
        'category_id',
        'day_integral',
        'week_integral',
        'month_integral',
        'avatar'
    ];

    protected $hidden = [
        'password',
        'remember_token',
        'super_admin',
        'created_at',
        'updated_at'
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }

    /**
     * 身份证加密
     *
     * @param $value
     * @return string|string[]
     */
    public function getIdCardAttribute($value)
    {
        return str_replace(substr($value, 6, 8), '********', $value);
    }

    // 和部门的关联
    public function section()
    {
        return $this->belongsToMany(Section::class, 'user_has_section', 'user_id', 'section_id')
            ->withPivot('id')
            ->using(UserHasSection::class);
    }

    /**
     * 定义修改器  密码加密
     * @param $password string 需要修改的字段
     */
    public function setPasswordAttribute(string $password)
    {
        $this->attributes['password'] = bcrypt($password);
    }

    // 和考试安排的关联
    public function examination()
    {
        return $this->hasMany(Examination::class, 'user_id', 'id');
    }

    public function operation()
    {
        return $this->hasMany(OperationLog::class, 'id', 'user_id');
    }
}
